<template>
  <div class="share-media">
    <Desktop v-if="isDesktop" :id="id" :share-aff="shareAff" @shared-feed="buildSchema"></Desktop>
    <Mobile
      v-else
      :id="id"
      :share-aff="shareAff"
      @shared-feed="buildSchema"
      @change:fpar="(v) => (logoOpacity = v)"
    ></Mobile>
    <LogoPanel class="logo" :style="{ opacity: logoOpacity }"></LogoPanel>
    <Jsonld :schema="schema"></Jsonld>
  </div>
</template>

<script setup>
import { ref, shallowRef } from 'vue'
import { useRoute } from 'vue-router'
import { storeToRefs } from 'pinia'
import { useAppStore } from '@/store/app'
import { useCreatorStore } from '@/store/creator'
import { useHeadStore } from '@/store/head'
import asyncCompWithLoading from '@/utils/async-comp-with-loading'
import { toDate } from '@/utils/string-helper'
import LogoPanel from '@/components/cards/LogoPanel.vue'
import Jsonld from '@/components/common/Jsonld.vue'
import { MEDIA_TYPE } from '@/constant/publish'

const Desktop = asyncCompWithLoading(() => import('./Desktop.vue'))
const Mobile = asyncCompWithLoading(() => import('./Mobile.vue'))

const appStore = useAppStore()
const { isDesktop } = storeToRefs(appStore)
const { getCreator } = useCreatorStore()

const route = useRoute()
const { id } = route.params
const { share_aff: shareAff } = route.query

const logoOpacity = ref(1)

const { toMediaHead } = useHeadStore()

const schema = shallowRef(null)
async function buildSchema(feed) {
  const creator = await getCreator(feed.aff)
  schema.value = {
    '@context': 'https://schema.org',
    '@type':
      feed.type === MEDIA_TYPE.VIDEO ? 'VideoObject' : feed.type === MEDIA_TYPE.IMAGE ? 'ImageObject' : 'MediaObject',
    name: feed.content,
    thumbnailUrl: import.meta.env.VITE_APP_URL + import.meta.env.VITE_APP_OG_IMAGE,
    uploadDate: toDate(feed.display_at).toISOString(),
    duration: feed.type === MEDIA_TYPE.VIDEO ? feed.video_time : undefined,
    contentUrl: feed.share_url.replace(/\?share_aff=\d*/, ''),
    interactionStatistic: {
      '@type': 'InteractionCounter',
      interactionType: 'https://schema.org/LikeAction',
      userInteractionCount: feed.like,
    },
    author: {
      '@type': 'Person',
      name: feed.author?.nickname,
      alternateName: '@' + feed.author?.username,
      identifier: `${feed.author?.aff}`,
      url: creator.share_url,
    },
    publisher: {
      '@type': 'Organization',
      name: 'Fantasi',
      logo: {
        '@type': 'ImageObject',
        url: import.meta.env.VITE_APP_URL + import.meta.env.VITE_APP_OG_IMAGE,
      },
    },
    keywords: feed.tags,
  }

  toMediaHead(feed)
}
</script>

<style lang="scss" scoped>
.share-media {
  width: 100%;
  height: 100%;
  position: relative;

  .logo {
    position: absolute;
    top: 1.25rem;
    left: 1.25rem;
  }
}
</style>
